package com.tarena.lbs.user.service.impl;

import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.dao.repository.UserRepository;
import com.tarena.lbs.user.dao.repository.UserTagsRepository;
import com.tarena.lbs.user.pojo.param.UserParam;
import com.tarena.lbs.user.pojo.param.UserTagsParam;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.pojo.po.UserTagsPO;
import com.tarena.lbs.user.pojo.vo.UserVO;
import com.tarena.lbs.user.service.UserService;
import com.tarena.lbs.user.utils.RandomUserName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserTagsRepository userTagsRepository;


    @Override
    public void register(UserParam param) throws BusinessException {
        String phone = param.getPhone();
        Long count = userRepository.countUserByPhone(phone);
        Asserts.isTrue(count>0,new BusinessException("-2","手机号已经存在"));
        //2.封装数据
        UserPO poParam = assembleUserPO(param);
        //3.直接写入数据库
        userRepository.save(poParam);
    }

    @Override
    public UserVO detail() throws BusinessException {
        //1.解析jwt 拿到userPrinciple
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        Integer userId = userPrinciple.getId();
        //2.仓储层查询唯一的po
        UserPO po = userRepository.getById(userId);
        Asserts.isTrue(po==null,new BusinessException("-2","用户信息不存在"));
        //3.转化vo
        UserVO vo=new UserVO();
        BeanUtils.copyProperties(po,vo);
        return vo;
    }

    @Override
    public void bindUserTags(UserTagsParam param) throws BusinessException {
        log.debug("用户标签绑定，入参：{}", param);

        // 1. 获取当前登录用户信息
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null, new BusinessException("-2", "用户未登录"));
        Integer userId = userPrinciple.getId();

        // 2. 参数校验
        Asserts.isTrue(param == null, new BusinessException("-2", "参数不能为空"));
        Asserts.isTrue(org.apache.commons.lang3.StringUtils.isBlank(param.getTagIds()),
                new BusinessException("-2", "标签ID不能为空"));

        // 3. 先删除用户原有的标签绑定关系
        userTagsRepository.deleteByUserId(userId);

        // 4. 解析标签ID字符串并保存新的绑定关系
        String[] tagIdArray = param.getTagIds().split(",");
        List<UserTagsPO> userTagsList = new ArrayList<>();

        for (String tagIdStr : tagIdArray) {
            try {
                Integer tagId = Integer.parseInt(tagIdStr.trim());
                UserTagsPO userTagsPO = new UserTagsPO();
                userTagsPO.setUserId(userId);
                userTagsPO.setTagId(tagId);
                userTagsList.add(userTagsPO);
            } catch (NumberFormatException e) {
                log.warn("无效的标签ID：{}", tagIdStr);
                throw new BusinessException("-2", "标签ID格式不正确：" + tagIdStr);
            }
        }

        // 5. 批量保存标签绑定关系
        if (!userTagsList.isEmpty()) {
            userTagsRepository.batchSave(userTagsList);
        }

        // 6. 更新用户状态为已绑定标签
        UserPO userPO = userRepository.getById(userId);
        if (userPO != null) {
            userPO.setStatus(1); // 1表示已绑定标签
            userRepository.update(userPO);
        }

        log.info("用户标签绑定成功，用户ID：{}，标签ID：{}", userId, param.getTagIds());

    }

    private UserPO assembleUserPO(UserParam param) {
        UserPO po=new UserPO();
        BeanUtils.copyProperties(param,po);
        //补充必要数据 用户状态 0表示没有绑定标签 1 表示绑定了标签
        po.setStatus(0);
        //用户昵称 注册时候 不是用户填写的 为了快速注册 我们随机生成一个
        String randomName = RandomUserName.createRandomName();//老 大 小  张王李赵
        po.setNickName(randomName);
        po.setUserName(randomName);
        //注册时间
        po.setRegTime(new Date());
        return po;
    }






}
